package com.skit.mine.ui;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.skit.common.base.BaseActivity;
import com.skit.common.bean.StatusResult;
import com.skit.common.bean.User;
import com.skit.common.bean.UserInfo;
import com.skit.common.config.RetrofitClient;
import com.skit.common.config.RouteConfig;
import com.skit.common.http.HttpUtils;
import com.skit.common.manager.UserManager;
import com.skit.common.utils.ToastUtils;
import com.skit.mine.R;
import com.skit.mine.adapter.InfoListAdapter;
import com.skit.mine.databinding.UserInfoActivityLayoutBinding;
import com.skit.mine.fragment.DepartmentBottomSheetFragment;
import com.skit.mine.fragment.EthnicBottomSheetFragment;
import com.skit.common.retrofit.UserProtocol;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since 2020/5/23
 */

@Route(path = RouteConfig.UserRoute.USER_INFO)
public class UserInfoActivity extends BaseActivity {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
    UserInfoActivityLayoutBinding binding;
    InfoListAdapter adapter;
    ProgressDialog progressDialog;

    private List<String[]> list = new ArrayList<>();
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.user_info_activity_layout);

        setSupportActionBar(binding.toolbar);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        progressDialog = new ProgressDialog(this);
        adapter = new InfoListAdapter(list);
        binding.baseInfoRecyclerView.setAdapter(adapter);
        binding.baseInfoRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        listener();

        user = UserManager.getUser();
        if (user == null) return;
        setData(user);
        getData(user);
    }

    private void listener() {
        adapter.setOnItemClickListener((view, position) -> {
            switch (list.get(position)[0]) {
                case "性别":
                    updateSex(position);
                    break;

                case "学院":
                    if (user.getUserInfo().getDepartment() == null) {
                        departmentBottomSheetDialog();
                    } else {
                        ToastUtils.showToast("不可更改");
                    }
                    break;

                case "专业班级":
                    if (user.getUserInfo().getDepartment() == null) {
                        ToastUtils.showToast("请先设置学院");
                    } else {
                        ToastUtils.showToast("不可更改");
                    }
                    break;
                case "民族":
                    EthnicBottomSheetFragment ethnicBottomSheetFragment = EthnicBottomSheetFragment.newInstance();
                    ethnicBottomSheetFragment.show(getSupportFragmentManager(), "选择民族");
                    ethnicBottomSheetFragment.setOnFinishListener(() -> {
                        user = UserManager.getUser();
                        if (user == null) return;
                        getData(user);
                    });
                    break;
            }
        });
    }

    private void departmentBottomSheetDialog() {
        DepartmentBottomSheetFragment departmentBottomSheetFragment = DepartmentBottomSheetFragment.newInstance();
        departmentBottomSheetFragment.show(getSupportFragmentManager(), "学院");
        departmentBottomSheetFragment.setOnFinishListener(() -> {
            user = UserManager.getUser();
            if (user == null) return;
            getData(user);
        });
    }


    private void updateSex(int position) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(UserInfoActivity.this);
        String[] strings1 = {"男", "女"};
        dialog.setItems(strings1, (dialog1, which) -> {
            progressDialog.setMessage("正在请求。。");
            progressDialog.setCancelable(false);
            progressDialog.show();
            UserProtocol userProtocol = RetrofitClient.getService(UserProtocol.class);
            Call<StatusResult<String>> update = userProtocol.update(user.getToken(), user.getId(), "sex", String.valueOf(which + 1));
            HttpUtils.doRequest(update, result -> {
                progressDialog.dismiss();
                if (result == null || !result.isSuccess()) {
                    if (result != null) ToastUtils.showToast(result.getMsg());
                    return;
                }

                UserInfo userInfo = user.getUserInfo();
                userInfo.setSex(which + 1);
                UserManager.saveUser(user);

                String[] strings = list.get(position);
                strings[1] = strings1[which];
                adapter.notifyDataSetChanged();
            });
        });
        dialog.show();
    }

    private void setData(User user) {
        UserInfo userInfo = user.getUserInfo();

        list.clear();
        list.add(new String[]{"姓名", user.getName()});
        int sex = userInfo.getSex();
        list.add(new String[]{"性别", sex == 0 ? "未知" : sex == 1 ? "男" : "女"});
        list.add(new String[]{"学号", userInfo.getStuID()});

        if (userInfo.getAdmissionDate() != null) {
            list.add(new String[]{"入学年份", simpleDateFormat.format(userInfo.getAdmissionDate())});
        }
        list.add(new String[]{"民族", userInfo.getEthnic() == null ? "未设置" : userInfo.getEthnic()});

        list.add(new String[]{"学院", userInfo.getDepartment() == null ? "未设置" : userInfo.getDepartment().getDepartmentName()});
        String s = userInfo.getClassNum() == null ? " " : userInfo.getClassNum();
        list.add(new String[]{"专业班级", userInfo.getSpecialities() == null ? "未设置" : userInfo.getSpecialities().getName() + s});

        list.add(new String[]{"邮箱", user.getEmail()});

        adapter.notifyDataSetChanged();
    }

    private void getData(User user) {
//        ProgressDialog progressDialog = new ProgressDialog(this);
//        progressDialog.setMessage("正在请求");
//        progressDialog.setCancelable(false);
//        progressDialog.show();
        UserProtocol userProtocol = RetrofitClient.getService(UserProtocol.class);
        Call<StatusResult<User>> userInfo = userProtocol.getUserInfo(user.getId(), user.getToken());
        HttpUtils.doRequest(userInfo, result -> {
//            progressDialog.dismiss();
            if (result == null || !result.isSuccess()) {
//                    Exception e = new Exception(result.getMsg());
                if (result != null) ToastUtils.showToast(result.getMsg());
                return;
            }
            User data = result.getData();
            if (data != null) {
                this.user = data;
                UserManager.saveUser(data);
                setData(data);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        menu.add(0, 0, 0, "修改")
//                .setIcon(ResourcesManager.getRes().getDrawable(R.drawable.ic_edit_black_24dp))
//                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        return true;
    }

}
